/**
 * 该场景固定长宽:
 *   1920 x 67
 * 
 * HTML 设置方案
 * #main
 *   #panel (canvas)
 */

import { Panel } from '../comps/bottom_slider/panel';

function createScene(context) {
	let t = new App(context);
	let scene = new context.Scene({
		require : ['zrender'],
		init : (libs) => t.init(libs),
		destroy : () => t.destroy(),
		collectInfo : () => t.collectInfo(),
		onMessage : (key, data) => t.onMessage(key, data),
		onTick : (assetId, data) => t.onTick(assetId, data),
	});
	t.sendStatus = scene.sendStatus;
	return scene;
}

/**
 * 底栏版弹幕机,
 * 初始风格: agdq2020_bottom_slider, 后期计划可以修改风格
 */

class App {
	roomId = 0;
	danmaku = null;

	/** @type {Panel} */
	panel = null;

	constructor(context) {
		this.context = context;
	}

	init(libs) {
		this.panel = new Panel({
			zrender: libs.zrender,
			context: this.context,
		});

		const roomStr = this.context.parseInitParam().room;
		if (roomStr) {
			const roomId = parseInt(roomStr);
			if (roomId) {
				this.handleAsset(roomId);
			}
		}

		this.panel._init();

		// test
		global.app = this;
	}

	collectInfo() {
		return {
			roomId : this.roomId
		};
	}

	onMessage(key, data) {
		switch (key) {
			case 'room': { // 修改房间号
				this.handleAsset(data.roomId);
				this.sendStatus();
			} return;
		}
		console.log("danmaku/bottom_slider 收到无法解析的命令: " + key, data);
	}

	sendStatus() {
		// 等待被覆盖
	}

	onTick(assetId, data) {
		if (this.danmaku != null) {
			this.danmaku.filterAssetTick(assetId, data);
		}
	}

	/**
	 * 创建资源、绑定资源
	 * @param {number} roomId B 站房间号, 例如 7734200
	 */
	handleAsset(roomId) {
		this.roomId = roomId;

		this.danmaku = new this.context.Danmaku(roomId);
		this.danmaku.createSource()
			.then(() => this.danmaku.openSource())
			.then(() => {
				this.danmaku.onDanmuReceived = (o) => this.panel.onDanmuReceived(o);
			});
	}
}

export default createScene;